using System;
using System.Collections.Generic;

namespace BoxBinary.AspectCache.Core.CacheManagement
{
    /// <summary>
    /// Dictionary of strings used to establish the single key of a cache entry. Typically contains instance-specific
    /// values such as a content ID to differentiate two cache entries of the same object type.
    /// </summary>
    public class CacheKeyParamsCollection : Dictionary<string, string>
    {
        /// <summary>
        /// Instantiates a new CacheKeyParamsCollection. Allows for convenient pre-population of the collection
        /// with new items by specifying key, value, key, value etc. in the constructor as a parameter array.
        /// </summary>
        /// <param name="keyValuePairParams"></param>
        public CacheKeyParamsCollection(params string[] keyValuePairParams)
        {
            // Check params array is valid key-value pairing
            if (keyValuePairParams.Length == 0 || keyValuePairParams.Length%2 != 0)
                throw new ArgumentException("Parameter array must be divisible by 2", "keyValuePairParams");

            for (int index = 0; index < keyValuePairParams.Length; index += 2)
            {
                string key = keyValuePairParams[index];
                string val = keyValuePairParams[index + 1];
                Add(key, val);
            }
        }

        /// <summary>
        /// Instantiates a new CacheKeyParamsCollection using the KeyValuePairs contained in a Dictionary as CacheKeyParams
        /// </summary>
        /// <param name="keyValueDictionary">Dictionary containing CacheKeyParams to add to the collection</param>
        public CacheKeyParamsCollection(Dictionary<string, string> keyValueDictionary)
        {
            foreach (var kvp in keyValueDictionary)
                Add(kvp.Key, kvp.Value);
        }

        /// <summary>
        /// An array of <see cref="KeyValuePair<string, string>"/> representing all the items in the dictionary.
        /// </summary>
        public KeyValuePair<string, string>[] Pairs
        {
            get
            {
                var internalList = new List<KeyValuePair<string, string>>();
                foreach (var pair in this)
                    internalList.Add(pair);
                return internalList.ToArray();
            }
        }
    }
}